<template>
  <Navheader :showSearch="isShowSearch" :isAdmin="false" @search="search" />
  <transition name="fade">
    <component
      v-if="showAnimation"
      :is="randomComponent"
      :waveOffsetRange="800"
    />
  </transition>
  <el-container class="zero-waste-community">
    <!-- 左侧导航 -->
    <asideLeft v-if="!$isMobile" :menuItems="menuItems" @show-editor="showEditor" @my-posts="onMyPosts" @search="search"
      @backToList="backToList" @menu-select="menuSelect" />
    <!-- 主内容区 -->
    <el-container v-if="!isShowEditor">
      <el-main class="main-content">
        <!-- 新增详情视图 -->
        <transition name="post-fade" mode="out-in">
          <postInfo v-if="showPostDetail" :selectedPost="selectedPost" :comments="comments" @backToList="backToList"
            @submit-comment="submitComment" />
          <div v-else class="content-wrapper">
            <!-- 帖子列表 -->
            <list @post-selected="handelPostSelected" :searchQuery="searchQuery" :tag="tag"/>
          </div>
        </transition>
      </el-main>
      <!-- 右侧边栏 -->
    </el-container>
    <MarkdownEditor v-else ref="editor" :uploadHandler="uploadImage" @change="handleChange" @publish="handlePublish"
      @cancel="handleCancel" :height="200" />
    <asideRight v-if="!$isMobile" :currentUser="currentUser" :recommendedPosts="recommendedPosts" :hot-tags="hotTags" @logout="logout"/>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, h, getCurrentInstance } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import Navheader from '../components/navHeader.vue'
import { useStore } from '../store/index.js'
import bkAnimation from '../components/bkAnimation.vue'
import RainEffect from '../components/RainEffect.vue'
import asideLeft from '../components/community/asideLeft.vue'
import asideRight from '../components/community/asideRight.vue'
import postInfo from '../components/community/postInfo.vue'

import list from '../components/community/list.vue'
import FlowBorder from './template.vue'
import MarkdownEditor from '../components/community/editor.vue';
import router from '../router/index.js'
import {
  Recycle,
  Sprout,
  ShoppingBag,
  Home,
  Search,
  PlusCircle,
  ThumbsUp,
  MessageCircle,
  Share2,
  Loader2,
  Flame,
  Circle,
  RefreshCw,
  ArrowLeft,
  MessageCircleMore,
  Archive
} from 'lucide-vue-next'
import network from '../api/index'
import { Message } from '@element-plus/icons'
import ajax from '../network/fetch.js'
import usePost from '../hook/post.js'
const { loadLock, loading, page, pageSize,searchQuery,tag, user, loadPosts, } = usePost()
const { communityApi,userApi,uploadApi,request } = network
const store = useStore()
const menuItems = [
  { icon: Archive, label: '全部' },
  { icon: Recycle, label: '回收利用' },
  { icon: Sprout, label: '可持续饮食' },
  { icon: ShoppingBag, label: '无包装购物' },
  { icon: Home, label: '环保家居' },
]
// 是否显示列表or帖子详情
const showPostDetail = ref(false)
// 选中的帖子信息
const selectedPost = ref({})
// 评论列表
const comments = ref([])
// 是否显示编辑器
const isShowEditor = ref(false)
// 编辑器内容
const content = ref('')
// 编辑器切换
const isShowSearch = ref(true)
const showEditor = (value) => {
  isShowEditor.value = value
}
// 随机加载动画状态
const showAnimation = ref(true);
const randomComponent = ref(null);
const editor = ref(null)
const currentUser = ref({
  name: user.username,
  avatar: user.avatar_url,
  points: 1250,
  posts: 8
})
const shareData = {
  title: '我的网站',
  text: '看看这个有趣的内容',
  url: 'https://example.com'
}
const recommendedPosts = ref([
  {
    id: 1,
    title: '家庭堆肥实用指南',
    excerpt: '分享我的厨房垃圾堆肥经验，让有机垃圾变废为宝...',
    author: '绿色生活家',
    likes: 156,
    comments: 23
  },
])
const hotTags = ref([
  '零浪费', '可持续生活', '环保DIY', '素食主义', '极简主义'
])

// 获取帖子信息
const getPostDetail = async (postId) => {
  showPostDetail.value = true
  const res = await request(communityApi.getPostDetail, { postId: postId })
  selectedPost.value = {
    ...res.data,
  }
  comments.value = res.data.comments.map(comment => ({
    ...comment,
  })
  )
}
// 提交评论
const submitComment = async (value) => {
  if (!value.trim()) return
  try {
    const res = await request(communityApi.commentPost, {
      postId: selectedPost.value.postId,
      content: value,
      userId: user.id
    }, 'post')
    ElMessage.success('评论成功')
    getPostDetail(selectedPost.value.postId)
  } catch (error) {
    ElMessage.error('评论失败')
  }
}
// 监听编辑器输入
const handleChange = (value) => {
  console.log(value)
}
// 上传文件
const uploadImage = async (file) => {
  try {
    const formData = new FormData();
    formData.append('common', file, file.name);
    const { data } = await request(uploadApi.upload, formData, 'POST')
    console.log('上传响应:', data);
    return data.url;
  } catch (error) {
    console.log('上传错误:', error);
  }
}
//取消发布
const handleCancel = (value) => {
  isShowEditor.value = value
  editor.value.clear()
}
// 获取帖子详情事件触发
const handelPostSelected = (value) => {
  isShowSearch.value = false
  getPostDetail(value)
}
// 返回列表
const backToList = () => {
  showPostDetail.value = false
  isShowSearch.value = true
}
// 侧边栏选中
const menuSelect = (value) => {
  console.log(value)
  store.isUserList = false
  if (value.label === '全部') {
    tag.value = ''
  }
  else{
    tag.value = value.label
  }
}
// 编辑器总数据
const handlePublish = async (value) => {
  console.log(value)
  try {
    const res = await request(communityApi.createPost, {
      userId: user.id,
      ...value,
      image_url: value.coverUrl,
    }, 'post')
    ElMessage.success('发布成功')
    isShowEditor.value = false
    loadPosts()
  } catch (error) {
    ElMessage.error('发布失败')
  }
}
// 我的帖子
const onMyPosts = (value) => {
  console.log(value)
}
const search = (value) => {
  searchQuery.value = value
  console.log('搜索内容:', value)
}
const logout = () => {
  ElMessage.success('退出登录成功')
  store.clearToken()
  router.push('/login')
}
// 随机选择组件
const getRandomComponent = () => {
  const components = [RainEffect, bkAnimation];
  const randomIndex = Math.floor(Math.random() * components.length);
  return components[randomIndex];
};

onMounted(() => {
  // 随机选择一个组件
  randomComponent.value = getRandomComponent();

  // 2秒后关闭动画
  setTimeout(() => {
    showAnimation.value = false;
  }, 7000);
});
</script>

<style lang="scss" scoped>
$primary-color: #10b981;
$secondary-color: #3b82f6;
$text-color: #1f2937;
$border-color: #e5e7eb;
$background-color: #f8fafc;

.zero-waste-community {
  margin-top: 60px;
  display: flex;
  height: calc(100vh - 60px);
}

.icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
  color: $text-color;
}

.singe-line {
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
  white-space: nowrap;
}

.main-content {
  overflow-y: hidden;
  background: $background-color;
  flex: 1;
}

.header-section {
  margin-bottom: 32px;

  .action-bar {
    display: flex;
    gap: 16px;
    padding: 16px 24px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);

    .search-input {
      flex: 1;

      .el-input__inner {
        height: 48px;
        border-radius: 8px;
        padding-left: 48px;
        font-size: 16px;
      }
    }

    .create-post-btn {
      height: 48px;
      padding: 0 24px;
      font-size: 16px;
      border-radius: 8px;
      transition: transform 0.2s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba($primary-color, 0.2);
      }
    }
  }
}

.loading-indicator {
  text-align: center;
  padding: 20px;
  color: $primary-color;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;

  .spin-icon {
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .zero-waste-community {
    margin-top: 40px;
    display: flex;
    // height: calc(100vh - 60px);
    background: $background-color;
  }
}

.post-fade-enter-active,
.post-fade-leave-active {
  transition: all 0.3s ease;
}

.post-fade-enter-from,
.post-fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>